package me.mingshan.leetcode;

import java.util.ArrayDeque;
import java.util.Queue;

/**
 * @author hanjuntao
 * @date 2025/8/27 0027
 */
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    public static void print(TreeNode root) {
        // 层序遍历逻辑：
        // 当遍历当前层时，将当前层的左右节点加入队列
        // 如何知道有没有遍历完当前层呢？

        // 层数
        int level = 0;
        // 当前层节点总数
        int curLevelNodesTotal = 0;
        // 当前层遍历的节点个数
        int cntNode = 0;

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        level++;
        curLevelNodesTotal++;

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            System.out.print(node.val + ",");
            if (node.left != null) {
                queue.add(node.left);
            }
            if (node.right != null) {
                queue.add(node.right);
            }
            cntNode++;

            // 当前层遍历结束
            if (cntNode == curLevelNodesTotal) {
                System.out.println();
                level++;
                curLevelNodesTotal = queue.size();
                cntNode = 0;
            }
        }
    }

    @Override
    public String toString() {
        return "val:" + val;
    }
}